import socket

# 创建 socket 对象
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 设置 socket 可重用
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# 绑定到本地地址和端口
server_socket.bind(('localhost', 8080))
# 开始监听，允许最多5个排队连接
server_socket.listen(5)

print("Server running on http://localhost:8080")

while True:
    # 接受客户端连接
    client_socket, address = server_socket.accept()
    print(f"Connection from {address}")

    # 接收客户端请求
    request = client_socket.recv(1024).decode('utf-8')
    print(f"Request:\n{request}")

    # 准备简单的 HTTP 响应
    response_body = "<html><body><h1>Hello from pure Python Web Server!</h1></body></html>"
    response = (
        "HTTP/1.1 200 OK\r\n"
        "Content-Type: text/html\r\n"
        f"Content-Length: {len(response_body)}\r\n"
        "\r\n"
        f"{response_body}"
    )

    # 发送响应给客户端
    client_socket.send(response.encode('utf-8'))

    # 关闭客户端连接
    client_socket.close()

# 注意：这个服务器需要手动用 Ctrl+C 停止